package org.elasticsearch.plugin.analysis.ik;

import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class LoggingFetchSubPhase implements FetchSubPhase {

    public static final String FIELD_NAME = "shenfl";

    @Override
    public void hitsExecute(SearchContext context, SearchHit[] hits) throws IOException {
        LoggingSearchExtBuilder ext = (LoggingSearchExtBuilder) context.getSearchExt(LoggingSearchExtBuilder.NAME);
        if (ext == null) {
            return;
        }
        int i = 0;
        for (SearchHit hit : hits) {
            Map<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(i));
            map.put("name", "shenfeilong");
            Map<String, DocumentField> all = new HashMap<>();
            all.putAll(hit.getFields());
            all.put(FIELD_NAME, new DocumentField(FIELD_NAME, Collections.singletonList(map)));
            hit.fields(all);
        }
    }
}